package com.qk.aop;

import cn.hutool.core.text.StrBuilder;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.qk.aop.anno.UseCache;
import com.qk.common.Result;
import com.qk.vo.portal.ReportOverviewVO;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

/**
 * @Author: zhangchuang
 * @Date: 2025/10/17 19:44
 * @Description: 缓存切面
 */
@Aspect
@Slf4j
@Component
@Order(1)
@SuppressWarnings("all")
public class PortalCacheAOP {

    private static final String CACHE_PORTAL_KEY_PREFIX = "qk:portal:";

    @Autowired
    private StringRedisTemplate redisClient;

    @Around("@annotation(com.qk.aop.anno.UseCache)")
    public Object aroundCache(ProceedingJoinPoint pjp) {
        Object res = null;
        String key = null;
        try {
            try {
                log.info("缓存切面开始执行");
                key = StrBuilder.create(CACHE_PORTAL_KEY_PREFIX, "reportOverview").toString();
                String jsonStr = redisClient.opsForValue().get(key);
                if (StrUtil.isNotBlank(jsonStr)) {
                    return JSONUtil.toBean(jsonStr, ReportOverviewVO.class);
                }
            } catch (Exception e) {
                log.error("redisClient.opsForValue().get(key) error: {}", e.getMessage());
            }
            res = pjp.proceed();
            try {
                if (ObjectUtil.isNotEmpty(res)) {
                    redisClient.opsForValue().set(key, JSONUtil.toJsonStr(res));
                }
            } catch (Exception e) {
                log.error("redisClient.opsForValue().set(key, JSONUtil.toJsonStr(vo)) error: {}", e.getMessage());
            }
        } catch (Throwable e) {
            res = Result.error("业务操作执行异常");
            log.info("缓存切面执行异常");
        }
        return res;
    }

}
